package com.bond.jumper.client.netty;

import com.bond.jumper.client.util.PropertiesUtils;
import com.bond.jumper.common.ChannelHolder;
import com.bond.jumper.common.decode.MessageToClientDecoder;
import com.bond.jumper.common.encode.MessageToServerEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.TimeUnit;

public class NettyClientRunner {

    private String ip;

    private int port;

    /**
     * 重新连接间隔时间，秒
     */
    private int reconnectInterval;

    private volatile boolean isRunning = true;

    private static Channel channel;

    private Bootstrap bootstrap;
    EventLoopGroup group = new NioEventLoopGroup();

    public void start() {
        ip = PropertiesUtils.getServerIp();
        port = PropertiesUtils.getServerPort();
        reconnectInterval = PropertiesUtils.getClientReconnetInterval();

        try {
            bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new MessageToClientDecoder());
                            ch.pipeline().addLast(new MessageToServerEncoder());
                            ch.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            doConnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }


    public void doConnect() {
        try {
            if (isRunning) {
                System.out.println("connect to server " + ip + ":" + port);
                //线程沉睡
                TimeUnit.SECONDS.sleep(reconnectInterval);
                //连接
                ChannelFuture future = bootstrap.connect(ip, port).sync();
                //拿到channel
                channel = future.channel();
                ChannelHolder.holdChannel(channel);
                //等待直到connection关闭
                channel.closeFuture().sync();
            }
        } catch (Exception e) {
            doConnect();
        }
    }

    public void stop() {
        isRunning = false;
        group.shutdownGracefully();
    }

}